<?
/*
 * Copyright (c) 2010 DC Team
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files(the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 */

define('DC', true);
include_once('../common.php');

$act = !isset($_REQUEST['act']) ? '' : trim($_REQUEST['act']);

//数据分批导入的数量
$per = '500';

//标准数据库比新数据库多的情况
//三个步骤, 1.表名对比  2.表名相同进行字段对比  3.表名相同且在指定中的表进行条数对比
if ($act == 'comparedb' || $act == 'tables') {
	if (empty($_POST['dbId'])) {
		exit('请选择要比较的库!');
	}

	//获取数据库id 连接数据库 kom
	$dbmainId   = $_POST['dbmainId'];
	$dbId       = explode('|',$_POST['dbId']);
	array_pop($dbId);
	$dbIds      = $dbId;
	$dbIds[]    = $dbmainId;
	$g_db       = mysqlConnect($dbIds);
	//获取数据库相关信息
	$maindata   = checkDatabase($dbmainId);
	$dbdata     = checkDatabase($dbId);

	if (count($maindata) == 0) {
		exit('<font color=red>主库为空,请检查!</font>');
	}

	if ($act == 'comparedb') {
		//生成比较结果
		$diffen = compareDb ($dbdata, $maindata, $dbId, $dbmainId);
	}else {
		$diffen = compareDb ($dbdata, $maindata, $dbId, $dbmainId, 0);
	}

	//输出比较的结果
	//选项卡
	$html = "<div><input type='checkbox' id='is_back' name='is_back' value='1' ><font color=red >是否备份</font>&nbsp;&nbsp;<input type='checkbox' id='is_comment' name='is_comment' value='1' ><font color=red >是否导入注释</font><b>主数据库为:{$dbmainId},以下为选中数据库的比较结果</b></div>";
	$html .= "<div id=\"lib_Tab1\" align=\"center\"><div class=\"lib_Menubox lib_tabborder\"><ul>";
	$nn = 1;
	$count = count($diffen);
	foreach ($diffen as $key => $value){
		$is_show = '';
		if ($nn == 1) {
			$is_show = "class='hover'";
		}
		$html .= "<li id=\"one{$nn}\" onclick=\"setTab('one',{$nn},{$count})\" {$is_show}>{$key}</li>";
		$nn ++;
	}
	$html .= "</ul></div><div class=\"lib_Contentbox lib_tabborder\">";
	//内容
	$n = 1;
	foreach ($diffen as $key => $value){
		$is_show = '';
		if ($n != 1) {
			$is_show = "style='display:none'";
		}
		$html .= "<div id=\"con_one_{$n}\" {$is_show}><form><table width=\"800\" align=\"center\" cellpadding=\"0\" cellspacing=\"0\" id=\"myTable\"><tr><th><input name='chkAll' type='checkbox' id='chkAll' onclick='CheckAll(this.form)' value='checkbox'> 全选</th><th>表名</th><th>数据库<font color=red>{$key}</font></th><th>字段缺少</th><th>字段多余</th></tr>";
		foreach ($value as $k => $val){
			//是否显示同步按钮
			$button = 1;
			if ($val['exist'] == '完全一致') {
				$button = 0;
			}
			if ($val['exist'] != '存在') {
				$str = '<font color=red>'.$val['exist'].'</font>';
			}else {
				$str = $val['exist'];
			}
			$html .= "<tr><td><input type='checkbox' name='dbids_{$key}' value='{$k}' /></td><td>{$k}</td><td>{$str}</td><td>{$val['lack']}</td><td>{$val['more']}</td></tr>";
		}
		if ($button && $act == 'comparedb') {
			$html .= "<tr><td colspan='6'>[数据库{$key}]&nbsp;&nbsp;";
			$html .= "<a href='#' onclick=\"if(confirm('确定添加缺少的表吗?')) asynDb('add', '{$key}', '{$dbmainId}');\">添加缺少的表</a> &nbsp;&nbsp;";
			$html .= "<a href='#' onclick=\"if(confirm('确定删除多余的表吗?')) asynDb('drop', '{$key}', '{$dbmainId}');\">删除多余的表</a> &nbsp;&nbsp;";
			$html .= "<a href='#' onclick=\"if(confirm('确定同步字段吗?')) asynDb('field', '{$key}', '{$dbmainId}');\">同步字段</a> &nbsp;&nbsp;";
			$html .= "<a href='#' onclick=\"if(confirm('确定删除多余字段吗?')) asynDb('del_field', '{$key}', '{$dbmainId}');\">删除字段</a> &nbsp;&nbsp;";
		}elseif ($act == 'tables'){
			$html .= "<tr><td colspan='6'>[数据库{$key}]&nbsp;&nbsp;";
			$html .= "<a href='#' onclick=\"if(confirm('确定同步固定表的数据吗?')) asynDb('specialdata', '{$key}', '{$dbmainId}');\">固定表数据同步</a>&nbsp;&nbsp;";
			$html .= "<a href='#' onclick=\"if(confirm('确定同步选中的这些表格的数据吗?')) asynDb('data', '{$key}', '{$dbmainId}');\">同步数据</a>&nbsp;&nbsp;";
		}
		$html .= "</td></tr></table></form></div>";
		$n++;
	}
	$html .= '</div>';
	echo $html;


} elseif ($act == 'autoasyn') { //一键同步
    if (empty($_POST['dbId'])) {
		exit('请选择要比较的库!');
	}

	//获取数据库id 连接数据库 kom
	$dbmainId   = $_POST['dbmainId'];
	$dbId       = explode('|',$_POST['dbId']);
	array_pop($dbId);
	$dbIds      = $dbId;
	$dbIds[]    = $dbmainId;
	$g_db       = mysqlConnect($dbIds);
	//获取数据库相关信息
	$maindata   = checkDatabase($dbmainId);
	$dbdata     = checkDatabase($dbId);

	if (count($maindata) == 0) {
		exit('<font color=red>主库为空,请检查!</font>');
	}

	$result = autorsyncDb($dbdata, $maindata, $dbId, $dbmainId);
	
	//输出结果
	print_r($result);
    
} elseif ($act == 'sqldb') { //一键同步
    if (empty($_POST['dbId'])) {
		exit('请选择要比较的库!');
	}

	//获取数据库id 连接数据库 kom
	$dbmainId   = $_POST['dbmainId'];
	$dbId       = explode('|',$_POST['dbId']);
	array_pop($dbId);
	$dbIds      = $dbId;
	$dbIds[]    = $dbmainId;
	$g_db       = mysqlConnect($dbIds);
	
	$sqlArr = explode(';', $configs['autosql']);
	
	foreach ($dbId as $sqldb) {
	    echo '<font color="red">数据库'.$sqldb.'SQL执行结果:</font><br>';
	    foreach ($sqlArr as $sqlv) {
	        if (strlen($sqlv) > 6) {
	            $sqlv = str_replace('\\', '', $sqlv);
	            $g_db[$sqldb]->query($sqlv);
	            if ( $g_db[$sqldb]->errno ){
	                echo 'sql: '.$sqlv.'执行失败';
	                printf("Errorcode: %d\n", $g_db[$sqldb]->errno);
	                echo '<br>';
	            } else {
	                echo 'sql: '.$sqlv.'执行成功<br>';
	            }
	        }
	    }
	}
	
	
    
} elseif ($act == 'comparetable' || $act == 'comparespe') {//表对比
	if (empty($_POST['tabId'])) {
		exit('你还没有做出选择!');
	}
	//连接数据库 kom
	$dbId = $_REQUEST['dbId'];
	$g_db = mysqlConnect($dbId);
	if($act == 'comparetable'){//指定表比较
		$mainTab = $_POST['mainTab'];
		$tabId   = explode('|',$_POST['tabId']);//获取表名
		array_pop($tabId);

		//获取表结构
		$maintable = checkTable($mainTab, $dbId);
		$table     = checkTable($tabId, $dbId);
		//比较表
		$diffen    = compareTable($table, $maintable[$mainTab]);
		//生成显示内容
		$html      = showCompare($diffen, $mainTab, $dbId);
		echo $html;
	}else {//固定表比较
		//获取固定类别
		$tabs = explode('|',$_POST['tabId']);
		array_pop($tabs);
		foreach ($tabs as $value){
			$config[$value] = $configs['type'][$value];
		}
		//循环比较每个类别
		foreach ($config as $value){
			$mainTab = $value[0];
			$tabId   = explode('|', $value[1]);//获取比较表名
			array_pop($tabId);

			//获取表结构
			$maintable = checkTable($mainTab, $dbId);
			$table     = checkTable($tabId, $dbId);
			//比较表
			$diffen    = compareTable($table, $maintable[$mainTab]);
			//生成显示内容
			$html      = showCompare($diffen, $mainTab, $dbId);
			echo $html;
		}
	}
}elseif ($act == 'add' || $act == 'drop' || $act == 'field' || $act == 'data' || $act == 'specialdata' || $act == 'del_field'){//多库同步处理
	//是否备份标识
	$is_back = ($_POST['is_back'] == 'undefined') ? 0 : $_POST['is_back'];
	$is_comment = ($_POST['is_comment'] == 'undefined') ? 0 : $_POST['is_comment'];

	if (empty($_POST['tabId']) && $act != 'specialdata') {
		exit('你还没有做出选择!');
	}
	//要处理的表id
	$tabId = explode('|', $_POST['tabId']);
	array_pop($tabId);

	//连接数据库 kom
	$dbId      = $_POST['dbId'];
	$dbmainId  = $_POST['dbmainId'];
	$dbIds     = array($dbId, $dbmainId);
	$g_db      = mysqlConnect($dbIds);

	if ($act == 'add') {//增加缺少的表
		$diff = array_diff($tabId, array_keys($_SESSION['diff'][$dbId]['lack']));
		if (count($diff)) {
			exit('你选择了并不缺少的表');
		}
		foreach ($tabId as $key => $value){

			//添加选中的表
			$sql    = "SHOW CREATE TABLE $value";
			$row    = $g_db[$dbmainId]->query($sql);
			$result = $row->fetch_assoc();
			$sqltext = $result['Create Table'];
			$g_db[$dbId]->query($sqltext);	
			if ( $g_db[$dbId]->errno ){
				printf("Errorcode: %d\n", $g_db[$dbId]->errno);
				exit('添加表'.$value.'失败');
			}					
		}
		exit('添加成功');
	}elseif ($act == 'drop'){//删除多余表
		$diff = array_diff($tabId, array_keys($_SESSION['diff'][$dbId]['more']));
		if (count($diff)) {
			exit('你选择了并不多余的表');
		}

		foreach ($tabId as $key => $value){
			//备份
			backupData($is_back, $value, $dbId);

			//删除选中的表
			$sql = "DROP TABLE $value";
			$g_db[$dbId]->query($sql);
			if ( $g_db[$dbId]->errno ){
				printf("Errorcode: %d\n", $g_db[$dbId]->errno);
				exit('删除表'.$value.'失败');
			}	
		}
		exit('删除成功');
	}elseif ($act == 'field' || $act == 'del_field'){//同步字段			
		if ($act == 'field') {
			$diff = array_diff($tabId, array_keys($_SESSION['diff'][$dbId]['field_lack']));
			if (count($diff)) {
				exit('你选择了字段并不缺少的表');
			}
			$sub = $_SESSION['diff'][$dbId]['field_lack'];//取缺少字段的表记录
		}else {
			$diff = array_diff($tabId, array_keys($_SESSION['diff'][$dbId]['field_more']));
			if (count($diff)) {
				exit('你选择了字段并不多余的表');
			}
			$sub = $_SESSION['diff'][$dbId]['field_more'];//取多余字段的表记录
		}		

		foreach ($tabId as $key => $value){
			//可以同步字段的表记录
			foreach ($sub[$value] as $k => $val){
				$need[] = $val[0];
			}

			$sql = "DESCRIBE $value";
			if ($act == 'field') {
				$row = $g_db[$dbmainId]->query($sql);
			}else {
				$row = $g_db[$dbId]->query($sql);
			}

			//取出注释
			$commentArr = array();
			if ( $is_comment == 1 && $act == 'field' ){
				$commentArr = getTableComment($dbmainId, $value);
			}
			
			//取出$dbId的字段集,用于判断是字段不一样是由名称还是字符类型造成的
			$r = $g_db[$dbId]->query("DESCRIBE $value");
			while ($res = $r->fetch_array()){				
				$out[] = $res[0];
				$field[$res[0]] = $res[1];
				$keysearch[$res[0]] = $res[3];//判断是否已有索引
			}

			$sqltext = "ALTER TABLE $value ";
			$sqlbak  = "ALTER TABLE $value ";

			$preField = '';//用于记录前一个字段
			
			
			while ($result = $row->fetch_assoc()){
				//属于字段有差别的集合
				if (@in_array($result['Field'], $need)) {
					//根据删除字段或添加字段执行不同的操作
					if ($act == 'del_field') {
						$sqlbak  .= "DROP {$result['Field']},";
					}else {
						$do  = "ADD ";
						//字符类型不一样,语句采用change
						if (@in_array($result['Field'], $out) && $act == 'field') {
							$do  = "CHANGE {$result['Field']}";
						}
						$sqltext .= "{$do} {$result['Field']} {$result['Type']} ";

						if (!stristr($result['Type'], 'int') && !stristr($result['Type'], 'decimal') && !stristr($result['Type'], 'float') && !stristr($result['Type'], 'double')) {
							$sqltext .= "CHARACTER SET utf8 COLLATE utf8_general_ci ";
						}
						if ($result['Null'] == 'NO') {
							$sqltext .= 'NOT NULL ';
						}else {
							$sqltext .= 'NULL ';
						}
						
						if ($result['Default'] != '') {
							$sqltext .= "DEFAULT '{$result['Default']}' ";
						}
						
						//注释
						if ( isset($commentArr[$result['Field']]) && !empty($commentArr[$result['Field']])){
							$sqltext .= " COMMENT '{$commentArr[$result['Field']]}' ";
						}
						
						if (!empty($preField)) {
							$sqltext .= " AFTER $preField,";
						}else {
							$sqltext .= ",";
						}
						//如果有索引,且要导入的表不存在此索引
						if (!empty($result['Key']) && ((isset($keysearch[$result['Field']]) && $keysearch[$result['Field']] == '') || !isset($keysearch[$result['Field']]))){
							if ( $result['Key'] == 'PRI' ){
								$sqltext .= " ADD PRIMARY KEY ({$result['Field']}),";
							}elseif ( $result['Key'] == 'UNI' ){
								$sqltext .= " ADD UNIQUE ({$result['Field']}),";
							}elseif ( $result['Key'] == 'MUL' ){
								$sqltext .= " ADD INDEX ({$result['Field']}),"; //最后一位必须为','，不能为空格 
							}
						}
						
					}					
				}
				$preField = $result['Field'];//记录前一字段
			}
			//备份表
			backupData($is_back, $value, $dbId);

			if ($act == 'field') {
				$sqltext = substr($sqltext, 0, -1);
				$g_db[$dbId]->query($sqltext);			
			}else {
				$sqlbak = substr($sqlbak, 0, -1);
				$g_db[$dbId]->query($sqlbak);				
			}
			if ( $g_db[$dbId]->errno ){
				printf("Errorcode: %d\n", $g_db[$dbId]->errno);
				exit('同步表'.$value.'失败，请检查表字段是否符添加要求');
			}
		}
		if ($act == 'field') {
			exit('字段同步成功');
		}else {
			exit('字段删除成功');
		}
	}elseif ($act == 'data' || $act == 'specialdata'){//同步数据
		//固定表同步还是选择表同步
		if ($act == 'specialdata') {
			$tabId = $configs['asyn'];
		}
		$tc = '0';
		$tcArr = '';
		foreach ($tabId as $v) {
		  if (!in_array($v, $configs['back']['主要表'])) {
		      $tcArr .= '['.$v.'] ';
		      $tc = '1';
		  }
		}
		if ($_REQUEST['ck'] == '0' && $tc == '1') {
		    exit('cf你同步的'.$tcArr.'表属于非基类数据,由玩家制造的数据,确定要覆盖目标机的相应玩家数据么?');
		}
		$diff = @array_diff($tabId, array_keys($_SESSION['diff'][$dbId]['interset']));
		if (count($diff)) {
			exit('你选择了不存在的表');
		}
		if (@array_intersect($tabId, $_SESSION['order'][$dbId])) {
			exit('你选择了字段顺序不一致的表');
		}
		foreach ($tabId as $key => $value){
			//备份表
			backupData($is_back, $value, $dbId);

			//导入数据
			$sql = "SELECT * FROM $value";
			$row = $g_db[$dbmainId]->query($sql);
			$num = $row->num_rows;
			
			if ($num > 0) {
			    if ($num > $per) {
			        $j = ceil($num/$per);
			        $g_db[$dbId]->query("TRUNCATE TABLE $value");//清空表
			        for ($g=0; $g<$j; $g++){
			            $sum = $g*$per;
			            $sql_lit = "SELECT * FROM {$value} LIMIT {$sum}, $per";
			            $row_lit = $g_db[$dbmainId]->query($sql_lit);
			            $num_lit = $row_lit->num_rows;
			            $sqltext = "INSERT INTO $value values ";
			            while ($result_lit = $row_lit->fetch_row()){
			                $num = count($result_lit);
			                $sqltext .= "(";
			                for ($i=0; $i<$num; $i++){
			                    $sqltext .= "'".addslashes($result_lit[$i])."',";
			                }
			                $sqltext = substr($sqltext, 0, -1);
			                $sqltext .= "),";
			            }
			            $sqltext = substr($sqltext, 0, -1);
			            
			            $g_db[$dbId]->query($sqltext);		    //执行导入
			            if ( $g_db[$dbId]->errno ){
			                printf("Errorcode: %d\n", $g_db[$dbId]->errno);
			                exit('<font color="red">导入表'.$value.'_'.$g."失败</font>\r\n");
			            }
			            $num = $g_db[$dbId]->affected_rows;
			            if ($num == -1) {
			                echo $value.'_'.$g."表同步失败,请检查表结构是否相同;\r\n";
			            } else{
			                echo $value.'_'.$g.'数据同步成功，生效'.$num."条记录\r\n";
			            }
			        }       
			    } else {
    				$sqltext = "INSERT INTO $value values ";
    				while ($result = $row->fetch_row()){
    					$num = count($result);
    					$sqltext .= "(";
    					for ($i=0; $i<$num; $i++){
    						$sqltext .= "'".addslashes($result[$i])."',";
    					}
    					$sqltext = substr($sqltext, 0, -1);
    					$sqltext .= "),";
    				}
    				$sqltext = substr($sqltext, 0, -1);
    				
    				$g_db[$dbId]->query("TRUNCATE TABLE $value");//清空表
    				$g_db[$dbId]->query($sqltext);		    //执行导入
    				if ( $g_db[$dbId]->errno ){
    				    printf("Errorcode: %d\n", $g_db[$dbId]->errno);
    				    exit('<font color="red">导入表'.$value."失败</font>\r\n");
    				}
    				$num = $g_db[$dbId]->affected_rows;
    				if ($num == -1) {
    				    echo $value."表同步失败,请检查表结构是否相同;\r\n";
    				} else{
    				    echo $value.'数据同步成功，生效'.$num."条记录 \r\n";
    				}
			    }
			}else {
				$sqltext = "TRUNCATE TABLE $value";
			}
		}
	}
}elseif ($act == 'backtable' || $act == 'deltable' ){//还原及删除表操作
	//连接数据库 kom
	$dbId = $_POST['dbId'];
	$g_db = mysqlConnect($dbId);
	$tabs = explode('|',$_POST['tabId']);
	array_pop($tabs);

	//判断有没为同一张表选择了多个备份
	if ($act == 'backtable') {
		foreach ($tabs as $value){
			$Arr      = explode('_', $value);
			$tables[] = $Arr[1];
		}
		if (count($tables) > count(@array_unique($tables))) {
			exit('你为同一张表选择了多个备份');
		}
	}

	foreach ($tabs as $value){
		//删除
		if ($act == 'deltable') {
			if ($_POST['key'] != $configs['key']){
				exit('密钥不正确，删除失败');
			}
			if(!stristr($value, 'backup0_0')){					
				backupData(1, $value, $dbId);
			}
			$sql = "DROP TABLE $value";
			$g_db[$dbId]->query($sql);
			if ( $g_db[$dbId]->errno ){
				printf("Errorcode: %d\n", $g_db[$dbId]->errno);
				exit('删除表'.$value.'失败');
			}	
		}else {
			$Arr = explode('0_0', $value);
			//删除原表
			$sql = "DROP TABLE {$Arr[1]}";
			$g_db[$dbId]->query($sql);

			//还原
			$sql = "RENAME TABLE $value TO {$Arr[1]} ";
			$g_db[$dbId]->query($sql);
			if ( $g_db[$dbId]->errno ){
				printf("Errorcode: %d\n", $g_db[$dbId]->errno);
				exit('还原表'.$value.'失败');
			}	
		}

	}
	exit('操作成功');
}elseif ($act == 'tabfield') {//同一库内字段处理
	//连接数据库kom
	$dbId = $_POST['dbId'];
	$g_db = mysqlConnect($dbId);

	$tabId   = $_POST['tabId'];
	$mainTab = $_POST['mainTab'];
	//备份表
	$is_back = ($_POST['is_back'] == 'undefined') ? 0 : $_POST['is_back'];
	backupData($is_back, $tabId, $dbId);

	//可以同步字段的表记录
	$need = array();
	$del  = array();
	$sub  = $_SESSION['diffen'][$tabId];
	foreach ($sub['lack'] as $k => $val){//取缺少字段的记录
		$need[] = $val[0];
	}
	foreach ($sub['more'] as $k => $val){//取多余字段的记录
		$del[] = $val[0];
	}

	//取出$dbId的字段集,用于判断是字段不一样是由名称还是字符类型造成的
	$r = $g_db[$dbId]->query("DESCRIBE $tabId");
	while ($res = $r->fetch_array()){
		$out[] = $res[0];
		$field[$res[0]] = $res[1];
	}

	$sql = "DESCRIBE $mainTab";
	$row = $g_db[$dbId]->query($sql);

	$preField = '';//用于记录前一个字段
	$sqltext = "ALTER TABLE $tabId ";
	while ($result = $row->fetch_assoc()) {
		//属于字段有差别的集合
		if (@in_array($result['Field'], $need)) {
			//字符类型不一样,语句采用change
			$do = "ADD ";
			if (@in_array($result['Field'], $out)) {
				$do = "CHANGE {$result['Field']}";
			}
			$sqltext .= "{$do} {$result['Field']} {$result['Type']} ";

			if (!stristr($result['Type'], 'int') && !stristr($result['Type'], 'decimal') && !stristr($result['Type'], 'float') && !stristr($result['Type'], 'double')) {
				$sqltext .= "CHARACTER SET utf8 COLLATE utf8_general_ci ";
			}
			if ($result['Null'] == 'NO') {
				$sqltext .= 'NOT NULL ';
			}else {
				$sqltext .= 'NULL ';
			}
			if ($result['Default']) {
				$sqltext .= "DEFAULT '{$result['Default']}'";
			}
			$sqltext .= " AFTER $preField,";
		}
		$preField = $result['Field'];
	}
	if (count($need)) {
		$sqltext = substr($sqltext, 0, -1);
		$g_db[$dbId]->query($sqltext);
		if ( $g_db[$dbId]->errno ){
			printf("Errorcode: %d\n", $g_db[$dbId]->errno);
			exit;
		}	
	}
	if (count($del)) {
		$sqlbak = "ALTER TABLE $tabId ";
		foreach ($del as $k => $val){
			if (@!in_array($val, $need)) {
				$sqlbak .= "DROP {$val},";
			}
		}
		$sqlbak = substr($sqlbak, 0, -1);
		$g_db[$dbId]->query($sqlbak);
		if ( $g_db[$dbId]->errno ){
			printf("Errorcode: %d\n", $g_db[$dbId]->errno);
			exit;
		}	
	}
	exit('同步成功!');
}elseif ($act == 'editconfig'){//处理配置文件

	$type = $_POST['type'];
	$data = @explode('@@@', $_POST['data']);
	array_pop($data);

	$str = "<?php
if (!defined('DC')) {
	die('It\'s allowed!'); 
}

define ( '_DO_DB_HOST', 'db_host' ); 
define ( '_DO_DB_USER', 'db_user' ); 
define ( '_DO_DB_PWD', 'db_pass' ); 
define ( '_DO_DB_NAME', 'db_name' ); 
define ( '_DO_DB_PORT', 'db_port' );\r\n";

	//数据库配置
	if ($type == 'adddb') {
		if (@array_key_exists($data[1], $g_db_conf[$data[0]])) {
			exit('服务器名称已存在');
		}
		$g_db_conf[$data[0]][$data[1]] = array('db_host' => $data[2], 'db_name' => $data[3], 'db_user' => $data[4], 'db_pass' => $data[5], 'db_port' => $data[6]);
	}elseif ($type == 'editdb') {
		if ($data[0] == $data[7] && $data[1] != $data[8]){
			if (@array_key_exists($data[1], $g_db_conf[$data[0]])) {
				exit('服务器名称已存在');
			}
		}
		unset($g_db_conf[$data[7]][$data[8]]);
		$g_db_conf[$data[0]][$data[1]] = array('db_host' => $data[2], 'db_name' => $data[3], 'db_user' => $data[4], 'db_pass' => $data[5], 'db_port' => $data[6]);
	}elseif ($type == 'deldb'){
		unset($g_db_conf[$data[7]][$data[8]]);
	}

	foreach ($g_db_conf as $key => $value){
		foreach ($value as $k => $val){
			$str .= "\$g_db_conf['{$key}']['{$k}'] = array('db_host' => '{$val['db_host']}', 'db_name' => '{$val['db_name']}',	'db_user' => '{$val['db_user']}', 'db_pass' => '{$val['db_pass']}',	'db_port' => '{$val['db_port']}');\r\n";
		}
	}

	//固定表配置
	if ($type == 'addtype') {
		if (@array_key_exists($data[0], $configs['type'])) {
			exit('该组合名称已存在');
		}
		$configs['type'][$data[0]] = array($data[1], $data[2]);
	}elseif ($type == 'edittype') {
		if ($data[0] != $data[3]) {
			if (@array_key_exists($data[0], $configs['type'])) {
				exit('该组合名称已存在');
			}
		}
		unset($configs['type'][$data[3]]);
		$configs['type'][$data[0]] = array($data[1], $data[2]);
	}elseif ($type == 'deltype'){
		unset($configs['type'][$data[3]]);
	}

	//比较条数与固定同步的表设置
	if ($type == 'update') {
		$configs['table'] = explode(',', $_POST['table']);
		$configs['asyn']  = explode(',', $_POST['asyn']);
		$configs['autosql'] = trim($_POST['autosql']);
		$configs['domain']  = trim($_POST['domain']);
		$configs['maindb']  = trim($_POST['maindb']);
		$configs['field']  = explode(',', $_POST['field']);
		$configs['index']  = explode(',', $_POST['index']);
	}

	//用户管理
	if ($type == 'adduser') {
		if (@array_key_exists($data[0], $configs['user'])) {
			exit('该用户已存在');
		}

		$configs['user'][$data[0]] = array('username' => $data[0], 'userpwd' => md5($data[1]));
	}elseif ($type == 'edituser') {
		if ($data[0] != $data[2]) {
			if (@array_key_exists($data[0], $configs['user'])) {
				exit('该用户已存在');
			}
		}
		unset($configs['user'][$data[2]]);
		$configs['user'][$data[0]] = array('username' => $data[0], 'userpwd' => md5($data[1]));
	}elseif ($type == 'deluser'){
		unset($configs['user'][$data[2]]);
	}
	
	//备份表配置
	if ($type == 'addback') {
		if (@array_key_exists($data[0], $configs['back'])) {
			exit('该名称已存在');
		}

		$configs['back'][$data[0]] = explode(',', $data[1]);			
	}elseif ($type == 'editback'){
		if ($data[0] != $data[1]) {
			if (@array_key_exists($data[0], $configs['back'])) {
				exit('该名称已存在');
			}
		}
		unset($configs['back'][$data[1]]);
		$configs['back'][$data[0]] = explode(',', $data[2]);			
	}elseif ($type == 'delback'){
		unset($configs['back'][$data[1]]);
	}

	foreach ($configs as $key => $value){
		$str .= "\$configs['{$key}'] = ".var_export($value, true).";\r\n";
	}

	editConfig('data.conf.php', $str);
	exit('处理成功');
}elseif ($act == 'backup'){//备份配置文件
	@chmod('include', 0777);
	chmod(ROOT.'include/data.conf.php', 0777);
	if(!copy(ROOT.'include/data.conf.php', ROOT.'include/data.bak.php')){
		exit('写入失败,可能是权限不足');
	}
}elseif ($act == 'editmmc'){//处理mmc配置
	$type = $_POST['type'];
	$data = @explode('@@@', $_POST['data']);
	array_pop($data);

	$str = "<?php
if (!defined('DC')) {
	die('It\'s allowed!'); 
}";

	//mmc管理
	if ($type == 'addmmc') {
		if (@array_key_exists($data[0], $g_mmc_tbconf)) {
			exit('该表已存在');
		}
		if ($data[1] == 'true') {
			$data[1] = true;
		}else{
			$data[1] = false;
		}
		
		$g_mmc_tbconf[$data[0]] = array('mmc' => $data[1], 'unkey' =>explode(',', $data[2]));
	}elseif ($type == 'editmmc') {
		if ($data[0] != $data[3]) {
			if (@array_key_exists($data[0], $g_mmc_tbconf)) {
				exit('该表已存在');
			}
		}
		if ($data[1] == 'true') {
			$data[1] = true;
		}else{
			$data[1] = false;
		}
		unset($g_mmc_tbconf[$data[3]]);
		$g_mmc_tbconf[$data[0]] = array('mmc' => $data[1], 'unkey' =>explode(',', $data[2]));
	}elseif ($type == 'delmmc'){
		unset($g_mmc_tbconf[$data[3]]);
	}

	foreach ($g_mmc_tbconf as $key => $value){
		$str .= "\$g_mmc_tbconf['{$key}'] = ".var_export($value, true).";\r\n";
	}

	editConfig('mmc.conf.php', $str);
	exit('处理成功');
}elseif ($act == 'batch'){//批量添加处理
	if (get_magic_quotes_gpc()) {
		$data = stripslashes($_POST['data']);
	}
	$_POST['type'] == 'batch_db' ? $file = '../include/data.conf.php' : $file = '../include/mmc.conf.php';	
	
	@chmod($file, 0777);
	$fp = @fopen($file, 'a+');
	if (@fwrite($fp, $data) or exit('写入失败, 请检查权限')) {
		echo '处理成功';
	}elseif (@fwrite($fp, $data) or exit('写入失败, 请检查权限')) {
		echo '处理成功';
	}
	@fclose($fp);
}elseif ($act == 'export' || $act == 'empty'){

	$tables = explode('|', $_POST['tables']);
	array_pop($tables);
	if (count($tables) == 0) {
		exit('请选择要备份的表');
	}

	$dbId = $_POST['dbId'];
	$g_db = mysqlConnect($dbId);

	$bak_sql = '';
	if ($act == 'export') {
		foreach ($tables as $key => $value){

			if ($_POST['table'] == 'table') {
				$sql = "SHOW CREATE TABLE {$value}";
				$result = $g_db[$dbId]->query($sql);
				$table_sql = $result->fetch_assoc();
				//	print_r($table_sql);exit;
				$bak_sql .= $table_sql['Create Table'].";\n\r";
			}
			if ($_POST['data'] == 'data') {
				$data_sql = dataSql($value, $dbId);
				if ($data_sql != '') {
					$bak_sql .= $data_sql."\n\r";
				}
			}
		}
		file_put_contents('../backsql/data.sql', $bak_sql);
		exit('<a href="backsql/data.sql">data.sql(右键下载)</a>');
	}elseif ($act == 'empty'){
		if ($_POST['key'] != $configs['key']){
			exit('密钥不正确，清除失败');
		}
			
		foreach ($tables as $key => $value){
			//备份表
			backupData(0, $value, $dbId);
			$sql = "TRUNCATE TABLE $value";
			$g_db[$dbId]->query($sql);			
		}
		exit('清除成功');
	}
}elseif ($act == 'getk'){//远程对比 select关联
	foreach ($g_db_conf[$_POST['domain']] as $key => $value){
		echo "<option value={$key}>数据库",$key,'</option>';
	}
}elseif ($act == 'netfield'){
	
	//是否备份标识
	$is_back = ($_POST['is_back'] == 'undefined') ? 0 : $_POST['is_back'];

	if (empty($_POST['tabId']) && $act != 'specialdata') {
		exit('你还没有做出选择!');
	}
	//要处理的表id
	$dbId  = $_POST['dbId'];
	$tabId = explode('|', $_POST['tabId']);
	array_pop($tabId);

	//连接数据库 kom
	$dbmainId = $_POST['dbmainId'];
	$g_db     = mysqlConnect($dbmainId);
	//print_r($_SESSION['diff'][$dbId]['field_more']);exit;
	//远程字段同步回本地
	
	$fieldmore = $_SESSION['diff'][$dbId]['field_more'];
	foreach ($fieldmore as $key => $value){
		if (empty($value)) {
			unset($fieldmore[$key]);
		}
	}

	$diff = array_diff($tabId, array_keys($fieldmore));
	if (count($diff)) {
		exit('你选择了字段并不多余的表');
	}

	$sub = $fieldmore;//取多余字段的表记录

	foreach ($tabId as $key => $value){
		//可以同步字段的表记录
		foreach ($sub[$value] as $k => $val){
			$need[$k] = $val[0];
		}

		/*	$sql = "DESCRIBE $value";
		if ($act == 'field') {
		$row = $g_db[$dbmainId]->query($sql);
		}else {
		$row = $g_db[$dbId]->query($sql);
		}
		*/
		//取出$dbId的字段集,用于判断是字段不一样是由名称还是字符类型造成的
		$r = $g_db[$dbmainId]->query("DESCRIBE $value");
		while ($res = $r->fetch_array()){
			$field[$res[0]] = $res[1];
			$field2[] = $res[0];// 用于判断字段位置
		}

		$sqltext = "ALTER TABLE $value ";
		$sqlbak  = "ALTER TABLE $value ";


		foreach ($fieldmore[$value] as $k => $val){
			if ($k != 0) {
				$preField = $_SESSION['netcom']['netdata'][$dbId][$value][$k-1][0];//$field2[$k-1];//用于记录前一个字段
			}else {
				$preField = '';
			}
			
			//属于字段有差别的集合 $val[0]字段名称  $val[1] 字段类型
			$old = empty($field[$val[0]]) ? '' :  $field[$val[0]];
			//$new = str_replace(array('<font color=blue>', '</font>'), '', $val[1]);
			$new = substr($val[1], 17, strpos($val[1],'</font>')-17);
			
			if ($new != $old && $old != '') {//字符类型不一样,语句采用change
				$do  = "CHANGE {$val[0]}";
			}else {
				$do  = "ADD ";
			}
			$sqltext .= "{$do} {$val[0]} {$new} ";

			$oldtype = substr($new, 0, strpos($new, '('));
			if (!stristr($oldtype, 'int') && !stristr($oldtype, 'decimal') && !stristr($oldtype, 'float') && !stristr($oldtype, 'double')) {
				$sqltext .= "CHARACTER SET utf8 COLLATE utf8_general_ci ";
			}
			if ($val[3] == 'NO') {
			$sqltext .= 'NOT NULL ';
			}else {
			$sqltext .= 'NULL ';
			}
			//$sqltext .= 'NOT NULL ';
			
			if ($val[2] != '') { 
			$sqltext .= "DEFAULT '{$val[2]}'";
			}
			if ($new != $old && $old != '' && $k == 0){
				$sqltext .= " ,";
			}else {
				$sqltext .= " AFTER $preField,";
			}
			
		}
		//echo $sqltext;exit;

		backupData($is_back, $value, $dbmainId);

		$sqltext = substr($sqltext, 0, -1);
		$g_db[$dbmainId]->query($sqltext);
		if ( $g_db[$dbId]->errno ){
			printf("Errorcode: %d\n", $g_db[$dbId]->errno);
			exit('字段同步失败');
		}
	}		
	exit('字段同步成功');
}elseif ( $act == 'allconfigtable' ){
	
	$mainTables = getMainTables();
	$str = '';
	foreach ( $mainTables as $key => $value ){
		if ( in_array( $value, $configs['back']['主要表']) ){
			$str .= '<font color="red">'.$value.'</font> ';
		}else{
			$str .= $value.' ';
		}
		
		if ( is_int(($key+1)/10) ){
			$str .= '<br />';
		}
	}
	echo $str;
}elseif ( $act == 'newspecialdata' ){//直接选库的固定表同步
	//获取数据库id 连接数据库 kom
	$dbmainId   = $_POST['dbmainId'];
	$dbId       = explode('|',$_POST['dbId']);
	array_pop($dbId);
	$dbIds      = $dbId;
	$dbIds[]    = $dbmainId;
	$g_db       = mysqlConnect($dbIds);
	
	$tabId = $configs['asyn'];
	$tc = '0';
	$tcArr = '';
	foreach ($tabId as $v) {
	    if (!in_array($v, $configs['back']['主要表'])) {
	        $tcArr .= '['.$v.'] ';
	        $tc = '1';
	    }
	}
	if ($_REQUEST['ck'] == '0' && $tc == '1') {
	    exit('cf你同步的'.$tcArr.'表属于非基类数据,由玩家制造的数据,确定要覆盖目标机的相应玩家数据么?');
	}

	foreach ( $dbId as $onedb ){
		echo '<font color="blue">'.$onedb.'库同步处理结果如下:</font><br/>';
		foreach ($tabId as $key => $value){			
			//导入数据
			$sql = "SELECT * FROM $value";
			$row = $g_db[$dbmainId]->query($sql);
			$num = $row->num_rows;

			if ($num > 0) {
			    if ($num > $per) {
			        $j = ceil($num/$per);
			        $g_db[$onedb]->query("TRUNCATE TABLE $value");//清空表
			        for ($g=0; $g<$j; $g++){
			            $sum = $g*$per;
			            $sql_lit = "SELECT * FROM {$value} LIMIT {$sum}, $per";
			            $row_lit = $g_db[$dbmainId]->query($sql_lit);
			            $num_lit = $row_lit->num_rows;
			            $sqltext = "INSERT INTO $value values ";
			            while ($result_lit = $row_lit->fetch_row()){
			                $num = count($result_lit);
			                $sqltext .= "(";
			                for ($i=0; $i<$num; $i++){
			                    $sqltext .= "'".addslashes($result_lit[$i])."',";
			                }
			                $sqltext = substr($sqltext, 0, -1);
			                $sqltext .= "),";
			            }
			            $sqltext = substr($sqltext, 0, -1);
			            
			            $g_db[$onedb]->query($sqltext);		    //执行导入
			            if ( $g_db[$onedb]->errno ){
			                printf("Errorcode: %d\n", $g_db[$onedb]->errno);
			                exit('<font color="red">导入表'.$value.'_'.$g.'失败</font><br/>');
			            }
			            $num = $g_db[$onedb]->affected_rows;
			            if ($num == -1) {
			                echo $value.'_'.$g.'表同步失败,请检查表结构是否相同;<br/>';
			            } else{
			                echo $value.'_'.$g.'数据同步成功，生效'.$num.'条记录 <br/>';
			            }
			        }       
			    } else {
    				$sqltext = "INSERT INTO $value values ";
    				while ($result = $row->fetch_row()){
    					$num = count($result);
    					$sqltext .= "(";
    					for ($i=0; $i<$num; $i++){
    						$sqltext .= "'".addslashes($result[$i])."',";
    					}
    					$sqltext = substr($sqltext, 0, -1);
    					$sqltext .= "),";
    				}
    				$sqltext = substr($sqltext, 0, -1);
    				
    				$g_db[$onedb]->query("TRUNCATE TABLE $value");//清空表
    				$g_db[$onedb]->query($sqltext);		    //执行导入
    				if ( $g_db[$onedb]->errno ){
    				    printf("Errorcode: %d\n", $g_db[$onedb]->errno);
    				    exit('<font color="red">导入表'.$value.'失败</font><br/>');
    				}
    				$num = $g_db[$onedb]->affected_rows;
    				if ($num == -1) {
    				    echo $value.'表同步失败,请检查表结构是否相同;<br/>';
    				} else{
    				    echo $value.'数据同步成功，生效'.$num.'条记录 <br/>';
    				}
			    }
			}else {
				$sqltext = "TRUNCATE TABLE $value";
			}
		}
	}		
	
} elseif ( $act == 'newspecialdata1' ){//直接选库的权限表同步
	//获取数据库id 连接数据库 kom
	$dbmainId   = $_POST['dbmainId'];
	$dbId       = explode('|',$_POST['dbId']);
	array_pop($dbId);
	$dbIds      = $dbId;
	$dbIds[]    = $dbmainId;
	$g_db       = mysqlConnect($dbIds);
	
	$tabId = array(
			  0 => 'tools_cate',
			  1 => 'tools_url',
			  2 => 'tools_user',
			  3 => 'tools_group'
			 );

	foreach ( $dbId as $onedb ){
		echo '<font color="blue">'.$onedb.'库同步处理结果如下:</font><br/>';
		foreach ($tabId as $key => $value){			
			//导入数据
			$sql = "SELECT * FROM $value";
			$row = $g_db[$dbmainId]->query($sql);

			if ($row->num_rows > 0) {
				$sqltext = "INSERT INTO $value values ";
				while ($result = $row->fetch_row()){
					$num = count($result);
					$sqltext .= "(";
					for ($i=0; $i<$num; $i++){
						$sqltext .= "'".addslashes($result[$i])."',";
					}
					$sqltext = substr($sqltext, 0, -1);
					$sqltext .= "),";
				}
				$sqltext = substr($sqltext, 0, -1);
			}else {
				$sqltext = "TRUNCATE TABLE $value";
			}
			$g_db[$onedb]->query("TRUNCATE TABLE $value");//清空表
			$g_db[$onedb]->query($sqltext);		    //执行导入
			if ( $g_db[$onedb]->errno ){
				printf("Errorcode: %d\n", $g_db[$onedb]->errno);
				exit('<font color="red">导入表'.$value.'失败</font><br/>');
			}
			$num = $g_db[$onedb]->affected_rows;
			if ($num == -1) {
				echo $value.'表同步失败,请检查表结构是否相同;<br/>';
			} else{
				echo $value.'数据同步成功，生效'.$num.'条记录 <br/>';
			}
		}
	}		
	
}
?>